<template>
  <view class="main">
	<tabar :current="2"></tabar>	
	<view class="class_h" style="background: linear-gradient(180deg, #91c8ec 0%, #fdfdfd 28.08%)">
	        <view class="top">血糖血压小程序</view>
	   
		    <view class="flex blood_top">
				<view class="flex">
					<image src="/static/resource/today.png" class="blood_sugar" v-if="blood_type ==1 " @click="select_blood(1)"></image>
					<image src="/static/resource/today1.png" class="blood_pressure" v-if="blood_type ==2 " @click="select_blood(1)"></image>
				</view>
				<view class="flex ml-30">
					<image src="/static/resource/record.png" class="blood_pressure" v-if="blood_type ==1 " @click="select_blood(2)"></image>
					<image src="/static/resource/record1.png" class="blood_sugar" v-if="blood_type ==2 " @click="select_blood(2)"></image>
				</view>
		    </view>
		   
		   <!-- 血糖 -->
		   <view class="flex total"  v-if="blood_type ==1 "> 
					  <div class="flex">
					    <view class="containers bg">
							<text style="margin-right: 15rpx;">您已连续打卡 </text>
							<view class="sign_day text-bold">
								{{userInfo.token?userInfo.sign_day:0}}
							</view>					
							<text style="margin-left: 15rpx;">天</text>
						</view>	
						<view class="flex  align-center text-center mt-5 ml-20"  @click="share_sign">
							<u-icon name="share" color="#2979ff" size="28"></u-icon>
							<text class=""> 分享</text>
						</view>
					    
					  </div>
			   	
					   
			   <view class="mr-20" style="overflow: hidden; width: 100%;  height: 90px;">				   
			     	<three-point-progress :marks="userInfo.token?userInfo.tags:marks" :value="userInfo.token?userInfo.sign_day:0" :images="userInfo.token?userInfo.member_receive:['/static/resource/a.png','/static/resource/a.png','/static/resource/a.png','/static/resource/a.png']" @imageClick="handleImageClick"/>
			   </view>
				
				
				<view class="sgin border-t mb-20">
					<view class="flex justify-between align-center text-center mb-20">
						<view class="flex">
							<image src="../../static/resource/sign_icon.png" mode="aspectFill" style="width: 18px;height: 18px;"></image>
							<text class="effect_t ml-15">签到</text>
						</view>
						
						<view class="flex" @click="userInfo.token?task():$routers.routeToLogin()">
							<span style="color: #287EE4;">建议测量 ></span>
						</view>
						
					</view>
					
					<view class="flex flex-wrap mt-20" style=" gap: 11px;">
						<view class="flex classify-cell-recom"  style="background-color: #F2F8FF;">
							<image src="/static/common/blood01.png" mode="scaleToFill" class="blood01"></image>
							<text class="blood_text">血糖测量 </text>
							<span :class="[userInfo.blood_type1?'finish_status':'wait_status']"> {{userInfo.blood_type1?'已完成':'未完成'}}</span>
							<view class="arrow-right" @click="doClass()">
								<u-icon name="arrow-right" color="#999999" size="24" ></u-icon>
							</view>
							
						</view>
						<view class="flex classify-cell-recom"  style="background-color: #FFEFD0;">
							<image src="/static/common/blood02.png" mode="scaleToFill" class="blood01"></image>
							<text class="blood_text">血压测量</text>
						   <span :class="[userInfo.blood_type2?'finish_status':'wait_status']"> {{userInfo.blood_type2?'已完成':'未完成'}}</span>
							<view class="arrow-right"  @click="doClass()">
								<u-icon name="arrow-right" color="#999999" size="24" ></u-icon>
							</view>
						</view>
						<view class="flex classify-cell-recom" style="background-color: #E6FAFB;">
							<image src="/static/common/blood03.png" mode="scaleToFill" class="blood02"></image>
							<text class="blood_text">健康饮食</text>
							<span :class="[userInfo.is_medication?'finish_status':'wait_status']"> {{userInfo.is_medication?'已完成':'未完成'}}</span>
							<view class="arrow-right" @click="upload()">
								<u-icon name="arrow-right" color="#999999" size="24" ></u-icon>
							</view>
						</view>
						
						<view class="flex classify-cell-recom" style="background-color: #F2F4FF;">
							<image src="/static/common/blood04.png" mode="scaleToFill" class="blood02"></image>
							<text class="blood_text mr-20"  >运动步数 {{step}} </text>
							<span :class="[userInfo.is_step?'finish_status':'wait_status']"> {{userInfo.is_step?'已完成':'未完成'}}</span>
							
							<view class="arrow-right" @click="getStepData">
								<u-icon name="arrow-right" color="#999999" size="24" ></u-icon>
							</view>
						</view>
					</view>
				</view>
				
				
				<view class="flex justify-start align-center text-center mt-20 mb-30" >
					<view class="flex">
						<image src="../../static/resource/preing.png" mode="aspectFill" style="width: 18px;height: 18px;"></image>
					</view>
					<text class="effect_t ml-15">当日总进度</text>
				</view>				
				
				<view class="progress-wrap" style="padding-bottom: 200rpx;">
				    <view class="progress-bg">
				      <view
				        class="progress-bar"
				        :style="{ width: progress + '%' }"
				      >
				        <text class="progress-text">{{ progress }}%</text>
				      </view>
				    </view>
				</view>
				<!-- <view class="flex submit_icon" @click="userInfo.token?task():$routers.routeToLogin()">
					 <image src="/static/resource/finish.png"  style="width: 686rpx;height: 88rpx;"></image>
				</view>	 -->
		   </view>	   
		   
		   <!-- 血压 -->
		   <view class="flex total"  v-if="blood_type ==2 ">
			   <view class="calendar">
			   	<view class="calendar-box">			   		
			   		<view class="header mt-20 mb-20">
			   			<image src="../../static/resource/left.png"  @click="prevMonth" style="width: 24px;height: 24px;"></image>
			   			<text class="ml-30 mr-30">{{ currentYear }}年{{ currentMonth + 1 }}月</text>
			   			<image src="../../static/resource/right.png"  @click="nextMonth" style="width: 24px;height: 24px;"></image>
			   		</view>
			   		<!-- <u-tabs :list="month" @click="month_click"></u-tabs> -->
			   		
			   		<view class="days-box mt-30  " style="border-top: 1rpx solid #EAEAEA !important;">
			   			<view class="days pt-15">
			   				<view class="day datess" v-for="(day, index) in days" :key="index">
			   					{{ day }}
			   				</view>
			   			</view>
			   			<view class="dates">
			   				<view class="date" v-for="(date, index) in monthDates" :key="index" @click="selectDate(date)"
			   					>
			   					<view class="date-item" :class="selectedDate && selectedDate.day === date&&selectedDate.year===currentYear&&selectedDate.month===currentMonth?'selected1':selectedDate && selectedDate.day === date?'selected1':'' ">
			   						<view class="" v-if="getSignData(date)==1">
										  <view class="flex signday">
											<text>{{date}}</text>
										  </view>
			   						</view>
									
									<view class="" v-if="getSignData(date)==2"  @click="select_sign(date)">
										  <view class="flex signdays">
											<text>{{date}}</text>
										  </view>
									</view>
			   						
			   						<view class="2"  v-if="getSignData(date)==3" >
			   						  {{ date&& date!==null ? date : '' }}
			   						</view>
			   						
			   					</view>
			   					
			   				</view>
			   			</view>
			   		</view>
			   		
			   	</view>
			   	
			   	<view class="flex mb-20" style="font-size: 28rpx;color: #000000;margin-left: -20rpx;">
			   		<view class="containers">
						<text style="margin-right: -15rpx;">您已连续打卡 </text>
						<view class="sign_day" style="height: 87px;width: 83px;">
							<text class="sign_days">{{userInfo.token?userInfo.sign_day:0}}</text>
						</view>					
						<text style="margin-left: -15rpx;">天</text>
					</view>	
			   	</view>
			   
			   </view>				
		   </view>				  
        </view>			
	    
		<!-- 图片 -->
		<u-popup :show="show" @close="goods_close"  mode="center" :round="10">
			<view class="goods_list">
				<view class="flex close_icon" @click="goods_close">
					<image src="../../static/resource/close.png" style="width: 74px;height: 30px;"></image>
				</view>
				<view class="flex gift-title">
					<text>实物奖励：（任选其一）</text>					
				</view>
				
				
				 <view class="gift-container">
				    <view class="item flex-direction" v-for="(item, index) in goodslist.list" :key="index">
				    <!--  <view class="dot"></view> -->
					  <image :src="item.goods_logo" class="goods_logo"></image>
				      <text class="label">{{ item.goods_title }}</text>
				    </view>
				</view>
				
				
				<!-- <view class="flex gift-title mt-15">
						<text>积分奖励：</text>	
						<text style="color: #287EE4;">35 </text>	
						<text class="ml-10">积分</text>	
				</view> -->
				<view class="flex submit_gift" @click="receive(goodslist.sign_day)">
					 <image src="/static/resource/gift_sub.png"  style="width: 210px;height: 44px;"></image>
				</view>				
			</view>
		</u-popup>
		
		<!-- 签到支付 -->
		<u-popup :show="pay_show" @close="sign_close"  mode="center" :round="10">
			<view class="goods_list">
				<view class="flex close_icon" @click="sign_close">
					<image src="../../static/resource/close.png" style="width: 74px;height: 30px;"></image>
				</view>
				
				
				
				<view class="flex gift-text mt-15" >
						每周第一次补签费用为 1 元。  同一周内再次补签时，费用将在上一次的基础上翻倍。  每周一系统会自动重置，从 1 元重新开始计算。
				</view>
				
				<view class="flex submit_gift" @click="order_signing()">
					 <image src="/static/resource/pay.png"  style="width: 290px;height: 44px;"></image>
				</view>				
			</view>
		</u-popup>
		
		
	<!-- 弹框部分 -->
	<u-popup
		  :show="userInfo.token && userInfo.is_information==0"
			  mode="center"
			  round="20"
			  :closeOnClickOverlay="false"
			  @close="showPopup = false"
			>
			  <view class="popup-box">
				<image
				  class="popup-icon"
				  src="/static/images/info.png"
				  mode="aspectFit"
				></image>
				<text class="popup-title">请完善个人信息</text>
				<text class="popup-desc mt-30">为了提供更好的服务，请先完善您的个人资料。</text>
				
				<view class="btn-group">
				  <u-button
					type="primary"
					color="#6EBA44"
					shape="circle"
					@click="goCompleteInfo"
				  >去完善</u-button>
				</view>
			  </view>
		</u-popup>
		
		
		
  </view>
</template>

<script>
	
	import tmenu from '@/components/menu/index.vue';
	import ThreePointProgress   from '@/components/dui-line-chart/ThreePointProgress.vue'
	export default {
		components: {
			ThreePointProgress,	
				tmenu,
		},		
		data() {
			const app = getApp()
			return {
				...getApp().globalData.config,
				currentDate: new Date(),
				blood_type:1,
				progress_day:2,
				marks:[7, 21, 42,66],
				progress:0,// 当前进度
				show:false,
				pay_show:false,
				items: ['鸡蛋', '低GI大米', '亚麻籽油'],
				signDayList:[
					
				],//签到记录
				pointslog_list:[],
				month: [{
					name: '1月',
				}, {
					name: '2月',
				}, {
					name: '3月'
				}, {
					name: '4月'
				}, {
					name: '5月'
				}, {
					name: '6月'
				}, {
					name: '7月'
				}, {
					name: '8月'
				}, {
					name: '9月'
				}, {
					name: '10月'
				}, {
					name: '11月'
				}, {
					name: '12月'
				}],
				userInfo:{},	
				signing_date:'',
				step:0,
				goods_list:[],
				goodslist:[]
			}
		},
		computed: {
			color() {
				let color = '#6EBA44';
				if (this.percent == 100) {
					color = '#5cb85c';
				}
				return color;
			},
			selectedDate(){
				let date = new Date()
				let year = date.getFullYear()
				let month = date.getMonth()
				let day = date.getDate()
				let obj={
					year,
					month,
					day
				}
				console.log(obj)
				return obj
			},
			currentYear() {
				return this.currentDate.getFullYear();
			},
			currentMonth() {
				return this.currentDate.getMonth();
			},
			days() {
				return ['日', '一', '二', '三', '四', '五', '六'];
			},
			monthDates() {
				const dates = [];
				const firstDay = new Date(this.currentYear, this.currentMonth, 1);
				const lastDay = new Date(this.currentYear, this.currentMonth + 1, 0);
		 
				// 填充前面的空白
				for (let i = 0; i < firstDay.getDay(); i++) {
					dates.push('');
				}
		 
				// 填充当前月的日期
				for (let i = 1; i <= lastDay.getDate(); i++) {
					let date = (new Date(this.currentYear, this.currentMonth, i)).getDate()
					dates.push(date);
				}
		 
				return dates;
			},
		},
	    
		onReady() {
		  this.$nextTick(() => {
		    this.option = { ...this.option }  // 强制触发更新
		  })
		},
		onShow(){
			this.getDayData()
			let user_info=uni.getStorageSync('userInfo');
			let that=this;
			if(user_info){
				let obj_data={
					token:user_info.token,
				    login_type:'app'
				};
				this.$http.getUser(obj_data).then(res=>{				
					if(res.resCode=='9999'){
						uni.setStorageSync('userInfo',res.data);	
					    that.userInfo=res.data	
						that.progress=res.data.progress_day
						that.step=res.data.step,
						that.goods_list=res.data.goods_list
					}				
				})	
			}else{
				 that.userInfo=''
			}
			// this.query_member()
		},
		
		methods: {
			...getApp().globalData.funcion,
			
			
			
			//签到海报
			share_sign(){
				uni.showLoading({
				  title: '加载中...',
				  mask: true // 防止触摸穿透
				})
				this.$http.pointsShare({type:1,token:uni.getStorageSync('userInfo').token}).then(res =>{
					if(res.resCode=='9999'){
						uni.downloadFile({
							url:  res.data.url,//必须是接口返回的路径，才可以保存到手机相册
							success(res) {
								uni.hideLoading()
								console.log(res,'res下载返回图片路径');
								
								// 图片保存到本地
								uni.saveImageToPhotosAlbum({
									
									filePath: res.tempFilePath,
									success(data) {
										uni.showToast({
											title: '保存成功',
											icon: 'success',
											duration: 2000
										});
									},
									fail(err) {
										console.log(err.errMsg);
										if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
											uni.showToast({
												title: '请允许访问相册后重试',
												icon: 'none',
												duration: 1000
											});
											setTimeout(() => {
												uni.openSetting();
											}, 1000);
										}
									},
									complete(res) {
										console.log('complete');
									}
								});
							}
						})
					}	
				})
			},
			
			doClass(){
				console.log('ok')
				
				this.$routers.router('/pages/class/index','switchTab') 
			},
			
			upload(){
					let that=this
					// 选择图片
					uni.chooseImage({
					  count: 1, // 默认9，设置图片的数量
					  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					  sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					  success: function (res) {
						// 成功选择图片后
						const filePath = res.tempFilePaths[0]; // 获取文件路径		
										
						let url=that.api_url+"index/medication";
						 console.log('url',url)
						// 上传图片
						uni.uploadFile({
						  url: url, // 服务器上传接口地址
						  filePath: filePath,
						  name: 'file', // 必须填写，后台用来接收文件
						  formData: {
							  token:uni.getStorageSync('userInfo').token	
						  },
						  success: function (res) {
							  	uni.showToast({title:'操作成功',icon:"success"})
						  },
						  fail: function (uploadFileErr) {
							console.log(uploadFileErr); // 上传失败的回调
						  }
						});
					  },
					  fail: function (chooseImageErr) {
						console.log(chooseImageErr); // 选择图片失败的回调
					  }
					});
				},			
			//完善信息
			goCompleteInfo(){
				this.$routers.router('/pages/pagesuser/member_set/member_base','navigateTo') 
			},
			
			
			//补签英文
			order_signing(){
				let that=this
				let currentMonth=this.currentMonth+1
				if(currentMonth<10) currentMonth="0"+currentMonth
				let data=this.signing_date
				if(data<10) data="0"+data
				let date=this.currentYear+'-'+currentMonth+'-'+data
				
				let obj_data={
					signing_date:date,
					token:uni.getStorageSync('userInfo').token					
				}
				
				if(!that.userInfo.wx_openid){
					uni.login({
					  provider: 'weixin',
					  success: function (res) {
							if (res.code) {
								obj_data.code=res.code								
								that.$http.doReSign(obj_data).then(rest=>{
									if(rest.resCode=='9999'){
										uni.requestPayment({
											provider: 'wxpay',
											timeStamp: rest.data.timeStamp,
											nonceStr: rest.data.nonceStr,
											package: rest.data.package,
											signType:rest.data.signType,
											paySign: rest.data.paySign,
											success: function (res) {		
												uni.showToast({title:'支付成功',icon:"success"}) 
												setTimeout(function(){
												   that.$routers.router('/pages/mine/index','switchTab') 
												},3000)
												
											},
											fail: function (err) {
												 uni.showToast({title:'请联系客服',icon:"none"}) 
											},									
										});								   								   
									}else{
									   uni.showToast({title:res.resMessage,icon:"none"}) 
									}											
								})								
							}
					    },
					})
				}else{
					that.$http.doReSign(obj_data).then(rest=>{
						if(rest.resCode=='9999'){
							console.log('rest',rest.data)
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: rest.data.timeStamp,
								nonceStr: rest.data.nonceStr,
								package: rest.data.package,
								signType:rest.data.signType,
								paySign: rest.data.paySign,
								success: function (res) {										
									uni.showToast({title:'支付成功',icon:"success"})
									setTimeout(function(){
									   that.$routers.router('/pages/mine/index','switchTab') 
									},3000)
								},
								fail: function (err) {
									 uni.showToast({title:'请联系客服',icon:"none"}) 
								},									
							});								   								   
						}else{
						   uni.showToast({title:res.resMessage,icon:"none"}) 
						}								
					})
				}
				
			},
			
			select_blood(type){
				this.blood_type=type
			},
			//点击奖励
			handleImageClick(item){
				
				let goods_list=this.goods_list
				if(goods_list[item].status==1){
					this.goodslist=goods_list[item]
					this.show=true
				}
			},
			goods_close(){
				this.show=false
			},
			
			//领取英文
			receive(sign_day){
				this.$routers.router('/pages/discover/index/index?sign_day='+sign_day,'navigateTo') 
			},
			//页面离开触发
			onHide(){
				this.pay_show=false
				this.show=false
			},
			
			//提交任务
			task(){
				this.$routers.router('/pages/discover/task/index','navigateTo') 
			},
			//判断哪天进行了签到
			getSignData(data){
				let currentMonth=this.currentMonth+1
			 	if(currentMonth<10) currentMonth="0"+currentMonth
				if(data<10) data="0"+data
				let date=this.currentYear+'-'+currentMonth+'-'+data
				// console.log('res',date)
				let falg = 3
				// this.signDayList.length>0&&this.signDayList.forEach(item=>{
				// 	if(item==date){
				// 		falg = true
				// 	}
				// })
				
				this.pointslog_list.length>0&&this.pointslog_list.forEach(item=>{
					if(item.create_at==date &&  item.status==1){
						falg = 1
					}
					if(item.create_at==date &&  item.status==0){
						falg = 2
					}
				})
				return falg
			},
			// 获取签到记录
			getDayData(){
				let that=this
			    let obj={year:this.currentYear,month:this.currentMonth+1,token:uni.getStorageSync('userInfo').token}
				this.$http.pointsLog(obj).then(res =>{
					 if(res.resCode=="9999"){	
						 that.signDayList=res.data.date;
						 that.pointslog_list=res.data.date_list;
						// uni.showToast({title:res.resMessage,icon:"none"})
					 }else{
						  that.signDayList=[];
						   that.pointslog_list=[];
						uni.showToast({title:res.resMessage,icon:"none"})
					 }
				})
			},
			//上个月
			prevMonth() {
				this.currentDate.setMonth(this.currentMonth - 1);
				this.currentDate = new Date(this.currentDate); // 触发视图更新
				this.getDayData()
			},
			   //下个月
			nextMonth() {
				
				this.currentDate.setMonth(this.currentMonth + 1);
				this.currentDate = new Date(this.currentDate); // 触发视图更新
				this.getDayData()
			},
			selectDate(date) {
				if (date) {
					this.$emit('dateSelected', date);
				}
			},
			
			//签到弹框
			select_sign(date){
				this.signing_date=date
				this.pay_show=true
			},
			//关闭签到
			sign_close(){
				this.pay_show=false
			},
			
			
			
			 async getStepData() {
				 let that = this
			      // 登录获取 code
			      const loginRes = await uni.login({ provider: 'weixin' })
			      const code = loginRes[1].code
			     console.log('code',code,loginRes)
				 // 显示加载中
				 uni.showLoading({
				   title: '加载中...',
				   mask: true // 防止用户操作
				 });
				 
			      // 请求授权
			      uni.authorize({
			        scope: 'scope.werun',
			        success: () => {
			          wx.getWeRunData({
						  
						 
						  
						  
			            success: async (res) => {
			              const { encryptedData, iv } = res
			
			              let obj={
							  token:uni.getStorageSync('userInfo').token,
							  code, 
							  encryptedData,
							   iv
						  }
						  console.log('obj',obj)
						  that.$http.decryptWeRun(obj).then(res=>{
							 if(res.resCode=="9999"){
								 that.step=res.data.step
								  uni.hideLoading();
							 	uni.showToast({title:res.resMessage,icon:"none"})
							 }else{
								  uni.hideLoading();
							 	uni.showToast({title:res.resMessage,icon:"none"})
							 }
						  })
						  console.log('obj',obj)
			            },
			            fail: () => {
							 uni.hideLoading();
			              uni.showToast({ title: '获取微信步数失败', icon: 'none' })
			            }
			          })
			        },
			        fail: () => {
						 uni.hideLoading();
			          uni.showToast({ title: '未授权微信运动', icon: 'none' })
			        }
			      })
			},
			
			formatDate(ts) {
			      const date = new Date(ts * 1000)
			      return `${date.getMonth() + 1}月${date.getDate()}日`
			}
			
		}
	  
	};
</script>

<style scoped>
  @import "./index.css";
</style>
